<script setup>

import { ref, computed } from 'vue'
import {
  roomBookApproveListService,
  cancelRoomBookService,
  approveRoomBookService,
  approveBatchService,
  getBookDetailService
} from '@/api/book.js'

import { ElMessage } from 'element-plus'
import useUserInfoStore from '@/stores/userInfo.js'
import {useRouter} from 'vue-router'
const router = useRouter()
const userInfoStore = useUserInfoStore();
const userInfo = ref({...userInfoStore.info})

const isAdmin = computed(() => {
  return userInfo.value.userRole === 'ADMIN';
});

//会议室搜索时选中的发布状态
const state = ref('')

//列表数据模型
const dataInfo = ref([])

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  getList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  getList()
}

const searchData = ref({});
const searchFormRef = ref();
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

//获取列表数据
const getList = async () => {
  let commonParams = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    roomname: (searchData.value.roomname || '').trim() || null,
  }
// 管理员参数
  const params1 = {
    ...commonParams,
    booker: (searchData.value.booker || '').trim() || null,
    bookphone: (searchData.value.bookphone || '').trim() || null,
  }
// 当前预约人参数
  const params2 = {
    ...commonParams,
    bookerid: userInfo.value.id
  }

  let result = await roomBookApproveListService(isAdmin.value ? params1 : params2);

//渲染视图
  total.value = result.data.total;
  dataInfo.value = (result.data.items || [])
}


getList();

import { createRoomTool } from '@/utils/common.js'

//添加表单数据模型
const addOrEditModel = ref(createRoomTool())


//控制添加会议室弹窗
const dialogVisible = ref(false);
//定义变量,控制标题的展示
const title = ref('');
// 定义操作状态
const isOpenBookWindow = ref(true);
const ruleFormRef = ref();


// 自定义校验手机号
const checkPhonePass = (rule, value, callback) => {
  let pattern = /(^1\d{10}$)|(^[0-9]\d{7}$)/;
  const pass = pattern.test(value);
  if (value && !pass) {
    callback(new Error("手机号格式错误"));
  } else {
    callback();
  }
}

//添加会议室表单校验
const rules = {
  timeslot: [
    { required: true, message: '请输入' + '预约时间', trigger: 'blur' },
  ],
  booker: [
    { required: true, message: '请输入' + '预约人', trigger: 'blur' },
  ],
  bookphone: [
    { required: true, message: '请输入' + '预约电话', trigger: 'blur' },
    { validator: checkPhonePass, trigger: 'blur' }
  ]
}

//展示编辑弹窗
const showDialog = (row) => {
  dialogVisible.value = true;
  title.value = '信息'
//数据拷贝
  addOrEditModel.value = {...row};


}






// 取消预约
const handleCancel = async(row) => {
  let result = await cancelRoomBookService({
    ...row,
    bookstate: '已取消'
  });
  if(result?.code === 0) {
    ElMessage.success('取消成功');
//刷新列表
    getList();
  } else {
    ElMessage.error('取消失败');
  }
}


const handleApprove = async (row, state) => {
  if (state === '不批准') {
    showRejectReason.value = true
    if (!rejectReason.value) {
      ElMessage.warning('请输入拒绝原因')
      return
    }
  }

  try {
    const params = {
      ...row,
      state,
      rejectReason: state === '不批准' ? rejectReason.value : null
    }

    const result = await approveRoomBookService(params)
    if (result?.code === 0) {
      ElMessage.success('操作成功')
      approveDialogVisible.value = false
      showRejectReason.value = false // 重置显示状态
      rejectReason.value = '' // 清空拒绝原因
      getList() // 刷新列表
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const selectedRows = ref([]); // 选中的预约记录

// 批量审核处理
const handleBatchApprove = (state) => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  batchApproveType.value = state
  // 如果是拒绝，初始化每条记录的拒绝原因
  if (state === '不批准') {
    selectedRows.value.forEach(row => {
      row.rejectReason = ''
    })
  }
  batchApproveDialogVisible.value = true
}

// 表格选择变化处理
const handleSelectionChange = (selection) => {
  // 只允许选择待审批的记录
  selectedRows.value = selection.filter(
      row => row.state === '待审批' && row.bookstate === '已预约'
  );
};

// 添加弹窗相关的响应式变量
const approveDialogVisible = ref(false)
const currentRecord = ref({})
const rejectReason = ref('')
const approveType = ref('approve') // 'approve' 或 'reject'
const showRejectReason = ref(false)

// 显示审核对话框
const showApproveDialog = (row) => {
  currentRecord.value = row
  rejectReason.value = ''
  showRejectReason.value = false
  approveDialogVisible.value = true
}

// 添加详情相关的响应式变量
const detailDialogVisible = ref(false)
const currentDetail = ref(null)

// 显示详情弹窗
const showDetailDialog = async (row) => {
  try {
    const result = await getBookDetailService(row.id)
    if (result.code === 0) {
      currentDetail.value = result.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error('获取预约详情失败')
    }
  } catch (error) {
    ElMessage.error('获取预约详情失败')
  }
}

// 获取审核状态对应的标签类型
const getStateTagType = (state) => {
  switch (state) {
    case '已批准':
      return 'success'
    case '不批准':
      return 'danger'
    case '待审批':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取预约状态对应的标签类型
const getBookStateTagType = (bookstate) => {
  switch (bookstate) {
    case '已预约':
      return 'success'
    case '已取消':
      return 'info'
    default:
      return 'info'
  }
}

// 添加批量审核对话框
const batchApproveDialogVisible = ref(false)
const batchApproveType = ref('已批准')

// 显示批量审核对话框
const showBatchApproveDialog = (type) => {
  batchApproveType.value = type
  batchApproveDialogVisible.value = true
}

// 处理批量审核确认
const confirmBatchApprove = async () => {
  if (batchApproveType.value === '不批准') {
    // 检查是否所有记录都填写了拒绝原因
    const missingReason = selectedRows.value.some(row => !row.rejectReason)
    if (missingReason) {
      ElMessage.warning('请为所有记录填写拒绝原因')
      return
    }
  }

  try {
    const recordsToApprove = selectedRows.value.map(row => ({
      id: row.id,
      state: batchApproveType.value,
      rejectReason: batchApproveType.value === '不批准' ? row.rejectReason : null
    }))

    const result = await approveBatchService(recordsToApprove)

    if (result.code === 0) {
      ElMessage.success(`批量${batchApproveType.value === '已批准' ? '通过' : '拒绝'}成功`)
      batchApproveDialogVisible.value = false
      getList()
      selectedRows.value = []
    } else {
      ElMessage.error(result.message || `批量${batchApproveType.value === '已批准' ? '通过' : '拒绝'}失败`)
    }
  } catch (error) {
    ElMessage.error('批量审核失败')
  }
}

// 添加点击不通过按钮的处理
const handleReject = (row) => {
  showRejectReason.value = true
  handleApprove(row, '不批准')
}

</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>预约记录</span>
        <div class="button-group" v-if="isAdmin">
          <el-button
              type="success"
              @click="handleBatchApprove('已批准')"
              :disabled="selectedRows.length === 0"
          >
            批量通过
          </el-button>
          <el-button
              type="danger"
              @click="handleBatchApprove('不批准')"
              :disabled="selectedRows.length === 0"
          >
            批量拒绝
          </el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form
        inline
        ref="searchFormRef"
        :model="searchData"
    >
      <el-form-item label="会议室：" prop="roomname">
        <el-input v-model="searchData.roomname" placeholder="请输入" clearable></el-input>
      </el-form-item>
      <template v-if="!!isAdmin">
        <el-form-item label="预约人：" prop="booker">
          <el-input v-model="searchData.booker" placeholder='请输入' clearable></el-input>
        </el-form-item>
        <el-form-item label="预约人电话：" prop="bookphone">
          <el-input v-model="searchData.bookphone" placeholder='请输入' clearable></el-input>
        </el-form-item>
      </template>


      <el-form-item>
        <el-button type="primary" @click="getList">搜索</el-button>
        <el-button @click="resetForm(searchFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 会议室列表 -->
    <el-table :data="dataInfo" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55"
          :selectable="row => row.state === '待审批' && row.bookstate === '已预约'"
      >
      </el-table-column>
      <el-table-column label="预约审批号" prop="id" width="80px"></el-table-column>
      <el-table-column label="会议室名称" prop="roomname"></el-table-column>
      <el-table-column label="容纳人数" prop="capacity"></el-table-column>
      <el-table-column label="地点" prop="location"></el-table-column>
      <el-table-column label="预约人" prop="booker"></el-table-column>
      <el-table-column label="预约电话" prop="bookphone"></el-table-column>
      <el-table-column label="审核状态" prop="state"></el-table-column>
      <el-table-column label="开始时间" prop="startTime"></el-table-column>
      <el-table-column label="结束时间" prop="endTime"></el-table-column>
      <el-table-column label="修改时间" prop="updateTime"></el-table-column>

      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button
              type="primary"
              size="small"
              @click="showApproveDialog(row)"
              v-if="!!isAdmin && ['待审批'].includes(row.state) && ['已预约'].includes(row.bookstate)"
          >
            审核
          </el-button>

          <el-button
              type="info"
              size="small"
              @click="showDetailDialog(row)"
          >
            预约详情
          </el-button>

          <el-popconfirm
              width="200"
              v-if="(!isAdmin || userInfo.id === row.bookerid) && ['待审批'].includes(row.state) && ['已预约'].includes(row.bookstate)"
              title="确认取消预约吗？"
              @confirm="handleCancel(row)"
          >
            <template #reference>
              <el-button
                  type="primary"
                  size="small"
                  style="margin-top: 8px;"
              >
                取消预约
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[10, 15, 20]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />

    <!-- 添加审核弹窗 -->
    <el-dialog
        v-model="approveDialogVisible"
        title="预约审核"
        width="500px"
    >
      <div class="approve-dialog-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="会议室">{{ currentRecord.roomname }}</el-descriptions-item>
          <el-descriptions-item label="预约人">{{ currentRecord.booker }}</el-descriptions-item>
          <el-descriptions-item label="预约人电话">{{ currentRecord.bookphone }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ currentRecord.startTime }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ currentRecord.endTime }}</el-descriptions-item>
        </el-descriptions>

        <!-- 修改拒绝原因输入框的显示条件 -->
        <div v-show="showRejectReason" class="reject-form">
          <el-form-item label="拒绝原因" required>
            <el-input
                v-model="rejectReason"
                type="textarea"
                rows="3"
                placeholder="请输入拒绝原因"
            ></el-input>
          </el-form-item>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button type="success" @click="handleApprove(currentRecord, '已批准')">通过</el-button>
          <el-button type="danger" @click="handleApprove(currentRecord, '不批准')">不通过</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="预约详情"
        width="40%"
        :close-on-click-modal="false"
    >
      <div class="detail-dialog-content" v-if="currentDetail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="当前状态">
            <div class="status-tags">
              <el-tag
                  :type="getStateTagType(currentDetail.state)"
                  class="status-tag"
              >
                审核状态：{{ currentDetail.state }}
              </el-tag>
              <el-tag
                  :type="getBookStateTagType(currentDetail.bookstate)"
                  class="status-tag"
              >
                预约状态：{{ currentDetail.bookstate }}
              </el-tag>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="会议室名称">
            {{ currentDetail.roomname }}
          </el-descriptions-item>
          <el-descriptions-item label="预约人">
            {{ currentDetail.booker }}
          </el-descriptions-item>
          <el-descriptions-item label="预约人电话">
            {{ currentDetail.bookphone }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ currentDetail.startTime }}
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            {{ currentDetail.endTime }}
          </el-descriptions-item>
          <el-descriptions-item label="活动名称">
            {{ currentDetail.title || '暂无' }}
          </el-descriptions-item>
          <el-descriptions-item label="预约理由">
            {{ currentDetail.reason || '暂无' }}
          </el-descriptions-item>
          <el-descriptions-item label="预约说明">
            {{ currentDetail.description || '暂无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加批量审核对话框 -->
    <el-dialog
        v-model="batchApproveDialogVisible"
        :title="batchApproveType === '已批准' ? '批量通过' : '批量拒绝'"
        width="600px"
    >
      <div class="batch-approve-content">
        <el-table :data="selectedRows" style="width: 100%">
          <el-table-column label="会议室" prop="roomname"></el-table-column>
          <el-table-column label="预约人" prop="booker"></el-table-column>
          <el-table-column label="拒绝原因" v-if="batchApproveType === '不批准'">
            <template #default="{ row }">
              <el-input
                  v-model="row.rejectReason"
                  type="textarea"
                  rows="2"
                  placeholder="请输入拒绝原因"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchApproveDialogVisible = false">取消</el-button>
          <el-button
              :type="batchApproveType === '已批准' ? 'success' : 'danger'"
              @click="confirmBatchApprove"
          >
            确认{{ batchApproveType === '已批准' ? '通过' : '拒绝' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<style lang="scss" scoped>


.book_form {
  ::v-deep(.el-input.el-input--suffix) {
    width: 190px;
  }

  ::v-deep(.el-form-item__label) {
    width: 200px!important;
  }
}

.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .button-group {
      display: flex;
      gap: 10px; /* 按钮之间的间距 */
    }
  }
}

.approve-dialog-content {
  padding: 20px;
}

.reject-form {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.button-group {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.detail-dialog-content {
  margin: 20px 0;

  :deep(.el-descriptions) {
    padding: 0 20px;
  }

  :deep(.el-descriptions__label) {
    width: 120px;
    justify-content: flex-end;
    font-weight: bold;
  }

  :deep(.el-descriptions__content) {
    padding: 12px 20px;
  }
}

.status-tags {
  display: flex;
  gap: 12px;

  .status-tag {
    padding: 6px 12px;
    font-size: 14px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>